﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace HZY.Framework.Dict.SourceGenerator
{
    [Generator]
    public class AopSourceGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context)
        {
        }

        public void Execute(GeneratorExecutionContext context)
        {
            //Debugger.Launch();

            //var aopAttributeSymbol = context.Compilation.GetTypeByMetadataName("AopAttribute");

            //foreach (var syntaxTree in context.Compilation.SyntaxTrees)
            //{
            //    var semanticModel = context.Compilation.GetSemanticModel(syntaxTree);

            //    foreach (var methodDeclaration in syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>())
            //    {
            //        var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
            //        if (methodSymbol.GetAttributes().Any(attr => attr.AttributeClass.Name == "AopAttribute"))
            //        {
            //            var code = GenerateAopCode(methodDeclaration, (IMethodSymbol)methodSymbol);
            //            context.AddSource($"{methodSymbol.Name}_Aop", SourceText.From(code, Encoding.UTF8));
            //        }
            //    }
            //}
        }

        private string GenerateAopCode(MethodDeclarationSyntax methodDeclaration, IMethodSymbol methodSymbol)
        {
            var builder = new StringBuilder();

            builder.AppendLine($"public partial class {methodSymbol.ContainingType.Name}");
            builder.AppendLine("{");

            var parameters = string.Join(", ", methodSymbol.Parameters.Select(p => $"{p.Type} {p.Name}"));
            builder.AppendLine($"    public partial {methodSymbol.ReturnType} {methodSymbol.Name}({parameters})");
            builder.AppendLine("    {");
            builder.AppendLine("        // Before");
            builder.AppendLine("       Console.WriteLine(\"之前\"); ");
            builder.AppendLine($"        var result = base.{methodSymbol.Name}({string.Join(", ", methodSymbol.Parameters.Select(p => p.Name))});");
            builder.AppendLine("        // After");
            builder.AppendLine("       Console.WriteLine(\"之后\"); ");
            builder.AppendLine("        return result;");
            builder.AppendLine("    }");

            builder.AppendLine("}");

            return builder.ToString();
        }
    }
}
